<template>
  <div class="wrapper" @click="jump">
    <div class="ring-bg"></div>
    <div class="ring-header">
      <div class="ios-tip" v-if="isIos && !clicked">点击屏幕 播放来电铃声</div>
      <div class="maximize-button">
        <img src="../assets/ami.png" style="color: #fff;width: 55px;">
      </div>
      <div class="ring-caller">
        <img :src=" headimgUrl || require('../assets/agr.png')" class="caller-avatar">
        <div class="ring-caller-title">{{nickname}}</div>

      </div>
      <div style="text-align: center;color: #ffffff;position: absolute;left: 0;right: 0;bottom: 130px;" v-if="answer">{{convertTime}}</div>
      <template v-if="answer">
        <mt-tabbar v-model="selected" style="background-color: transparent;bottom: 20px;">
          <mt-tab-item id="tab1">
            <img slot="icon" src="../assets/amq.png">
            静音
          </mt-tab-item>
          <mt-tab-item id="tab2"  >
            <img slot="icon" src="../assets/agw.png" @click.stop="hangup">
            挂断
          </mt-tab-item>
          <mt-tab-item id="tab3">
            <img slot="icon" src="../assets/amm.png">
            免提
          </mt-tab-item>
        </mt-tabbar>
      </template>
      <template v-else>
        <mt-tabbar v-model="selected" style="background-color: transparent;bottom: 20px;z-index: 9000 !important;">
          <mt-tab-item id="tab1" style="z-index: 9999 !important;">
            <img slot="icon" src="../assets/agw.png" @click.stop="hangup">
            拒绝
          </mt-tab-item>
          <mt-tab-item id="tab2" style="z-index: 9999 !important;">
            <img slot="icon" src="../assets/agf.png" @click="answerPlay">
            接听
          </mt-tab-item>
          <div id="music" style="display: none">
            <audio controls :src="audio" ref="audio" @ended="endTip"></audio>
          </div>
        </mt-tabbar>
      </template>

    </div>
    <keep-alive>
      <div id="audioBox" class="audio-hidden" style="display: none"></div>
    </keep-alive>

    <div @click.stop>
      <ProjectFrame v-if="showModalDialog"
                    @confirm="confirmShare"
                    @close="$router.push('/edit-audio/' + id)"
                    content="太好玩啦！分享给更多人！"
                    :negative="{text: '再次编辑'}"
                    :positive="{text: '分享'}"></ProjectFrame>
    </div>
    <div @click.stop="showShare = false">
      <Share v-if="showShare"></Share>
    </div>
  </div>
</template>

<script>
import ProjectFrame from '../components/ProjectFrame'
import Share from './Share'

const leftPad = (str, num, ch) => {
  str = str.toString()

  if (str === null || str === undefined) return str

  if (ch === 0) {
    ch = '0'
  } else if (ch) {
    ch = ch.toString()
  } else {
    ch = ' '
  }

  const len = num - str.length

  return len < 0 ? str.substr(0, num) : ch.repeat(len) + str
}

function formatSeconds (value) {
  var secondTime = parseInt(value) // 秒
  var minuteTime = 0 // 分
  var hourTime = 0 // 小时
  minuteTime = parseInt(secondTime / 60) + ''
  // 获取秒数，秒数取佘，得到整数秒数
  secondTime = parseInt(secondTime % 60) + ''

  return (minuteTime.length < 2 ? leftPad(minuteTime, 2, '0') : minuteTime ) +
    ':' + leftPad(secondTime, 2, '0')
}

export default {
  data () {
    console.log(this.$route.params.type)
    return {
      id: this.$route.params.id,
      type1: this.$route.params.type,
      headimgUrl: '',
      nickname: '~',
      audio: require('../assets/8521.mp3'),
      selected: 'tab1',
      answer: false,
      clicked: false,
      timeSpanList: [],
      answerTipListener: null,
      voiceUrlList: [],
      showModalDialog: false,
      showShare: false,
      time: 0,
      timeInterval: null,
      playEndedHandler: null,
      fended: null,
      isIos: navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    }
  },
  created () {
    this.$http.post('/biaobeihy/hy/findOneById', {
      id: this.id
    }).then(data => {
      Object.assign(this, data.data)
      const config = {
        title: '快来看看我制作的换音',
        desc: this.contentList.join('').substr(0, 25), // 分享描述
        link: location.protocol + '//' + location.host + '/#/connected/detail/' + this.id, // 分享链接
        imgUrl: this.headimgUrl // 活动图标
      }
      this.$util.initWxJs().then(() => {
        this.$wx.onMenuShareAppMessage(config)
        this.$wx.onMenuShareTimeline(config)
      })
    })
  },
  mounted () {
    if (this.$refs.audio) {
      this.$refs.audio.play()
    }
  },
  computed: {
    convertTime () {
      return formatSeconds(this.time)
    }
  },
  methods: {
    jump () {
      if (this.clicked) return
      this.clicked = true
      this.$refs.audio.play()
    },
    endTip () {
      this.$refs.audio.play()
    },
    answerPlay () {
      this.show()
      this.$refs.audio.pause()
      this.answer = true
      this.timeInterval = setInterval(() => {
        console.log(this.time)
        this.time++
      }, 1000)
    },
    show () {
      const self = this
      const copy = this.voiceUrlList.slice()
      const timeCopy = this.timeSpanList.slice()
      let myAudio = new Audio()
      myAudio.preload = true
      myAudio.controls = true
      myAudio.src = copy.shift() // 每次读数组最后一个元素
      myAudio.addEventListener('ended', this.playEndedHandler = playEndedHandler, false)
      myAudio.play()
      document.getElementById('audioBox').appendChild(myAudio)
      myAudio.loop = false // 禁止循环，否则无法触发ended事件

      if (this.voiceUrlList.length === 1) {
        function fended() {
          setTimeout(() => clearInterval(self.timeInterval), 1500)
          if (self.type1 === 'preview') {
            self.showModalDialog = true
          } else {
            self.$router.push('/home/' + self.id)
          }

          myAudio.removeEventListener('ended', self.fended, false)
        }
        myAudio.addEventListener('ended', self.fended = fended, false)
      }


      function playEndedHandler () {
        const time = timeCopy.shift()
        if (!document.getElementById('audioBox')) { return }
        console.log(time)
        myAudio.src = copy.shift()
        if (myAudio.src) {
          setTimeout(() => {
            myAudio.play()
          }, (time || 1) * 1000)
        }

        console.log(copy.length)
        if (!copy.length) {
          myAudio.removeEventListener('ended', this.playEndedHandler, false) // 只有一个元素时解除绑定

          function ended() {
            setTimeout(() => clearInterval(self.timeInterval), 1500)
            if (self.type1 === 'preview') {
              self.showModalDialog = true
            } else {
              self.$router.push('/home/' + self.id)
            }

            myAudio.removeEventListener('ended', ended, false)
          }
          myAudio.addEventListener('ended', ended, false)

        }
      }
    },
    hangup () {
      clearInterval(this.timeInterval)
      if (this.$refs.audio) {
        this.$refs.audio.pause()
      }
      var el = document.getElementById('audioBox')
      var childs = el.childNodes
      for (let i = childs.length - 1; i >= 0; i--) {
        childs[i].pause()
        childs[i].removeEventListener('ended', this.playEndedHandler, false)
        childs[i].removeEventListener('ended', this.fended, false)
      }
      for (let i = childs.length - 1; i >= 0; i--) {
        el.removeChild(childs[i])
      }

      console.log(this.type1)

      if (this.type1 === 'preview') {
        this.showModalDialog = true
      } else {
        this.$router.push('/home/' + this.id)
      }
    },
    confirmShare () {
      this.showModalDialog = false
      this.showShare = true
    }
  },
  beforeDestroy () {
    clearInterval(this.timeInterval)
  },
  components: {
    ProjectFrame,
    Share
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less" rel="stylesheet/less">
.wrapper {
  height: 100%;
  margin: 0;
  padding: 0;
}

.ring-bg {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: -1;
  background-color: #645c5a;
}

.ios-tip {
  position: fixed;
  right: 20px;
  top: 20px;
  font-size: 12px;
  color: #fff;
}
.ring-header {
  position: absolute;
  background: #645c5a;
  z-index:1;
  width:100%;
  height:100%;
  top:0px;
  left:0px;

  :global{
    .mint-tabbar {
      background-image: none;
    }

    .mint-tab-item.is-selected {
      background-color: transparent!important;
    }
  }

}
.maximize-button {
  position: absolute;
  margin-left: .266667rem;
  top: 1.24rem;
  left: .51rem;
  height: 1.92rem;
  padding-right: .2rem;
}
.ring-caller {
  position: absolute;
  top: 12.24rem;
  left: 0;
  right: 0;
  padding: 0 20px;
  text-align: center;
}
.ring-caller-title {
  text-align: center;
  margin-top: 12px;
  font-size: 1.5rem;
  color: #fff;
}
.ring-caller-caption {
  text-align: center;
  margin-top: 8rem;
  font-size: .65rem;
  color: #fff;
}
.caller-avatar {
  border-radius: 8px;
  width: 108px;
  height: 108px;
}
.ring-footer {
  position: fixed;
  bottom: 5rem;
}
.ring-footer #call-refuse {
  width: 4rem;
  float: left;
  left: 3.3rem;
}
.ring-footer #call-receive {
  width: 4rem;
  float: right;
  right: 3.3rem;
}

  .audio-hidden {
    display: none;
  }
</style>
